﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Application;
using Admin.NET.Core;
namespace Admin.NET.Application;

/// <summary>
/// 仓库表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class WarehouseModelService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<WarehouseModel> _warehouseModelRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public WarehouseModelService(SqlSugarRepository<WarehouseModel> warehouseModelRep, ISqlSugarClient sqlSugarClient)
    {
        _warehouseModelRep = warehouseModelRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询仓库表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询仓库表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<WarehouseModelOutput>> Page(PageWarehouseModelInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _warehouseModelRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.WareCode.Contains(input.Keyword) || u.WareName.Contains(input.Keyword) || u.WareAddr.Contains(input.Keyword) || u.WareNote.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WareCode), u => u.WareCode.Contains(input.WareCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WareName), u => u.WareName.Contains(input.WareName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WareAddr), u => u.WareAddr.Contains(input.WareAddr.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WareNote), u => u.WareNote.Contains(input.WareNote.Trim()))
            .WhereIF(input.WareVolume != null, u => u.WareVolume == input.WareVolume)
            .WhereIF(input.DepartmentId != null, u => u.DepartmentId == input.DepartmentId)
            .WhereIF(input.UserId != null, u => u.UserId == input.UserId)
            .WhereIF(input.WareType.HasValue, u => u.WareType == input.WareType)
            .WhereIF(input.WareLock.HasValue, u => u.WareLock == input.WareLock)
            .WhereIF(input.DeleteTimeRange?.Length == 2, u => u.DeleteTime >= input.DeleteTimeRange[0] && u.DeleteTime <= input.DeleteTimeRange[1])
            .Select<WarehouseModelOutput>();
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取仓库表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取仓库表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<WarehouseModel> Detail([FromQuery] QueryByIdWarehouseModelInput input)
    {
        return await _warehouseModelRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加仓库表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加仓库表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddWarehouseModelInput input)
    {
        var entity = input.Adapt<WarehouseModel>();
        if (await _warehouseModelRep.IsAnyAsync(u => u.WareName != null && u.WareName == input.WareName)) throw Oops.Oh("仓库名称不能为空已存在");
        return await _warehouseModelRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新仓库表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新仓库表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateWarehouseModelInput input)
    {
        if (await _warehouseModelRep.IsAnyAsync(u => u.Id != input.Id && u.WareName != null && u.WareName == input.WareName)) throw Oops.Oh("仓库名称不能为空已存在");
        var entity = input.Adapt<WarehouseModel>();
        await _warehouseModelRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除仓库表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除仓库表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteWarehouseModelInput input)
    {
        var entity = await _warehouseModelRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _warehouseModelRep.FakeDeleteAsync(entity);   //假删除
        //await _warehouseModelRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除仓库表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除仓库表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteWarehouseModelInput> input)
    {
        var exp = Expressionable.Create<WarehouseModel>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _warehouseModelRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _warehouseModelRep.FakeDeleteAsync(list);   //假删除
        //return await _warehouseModelRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 导出仓库表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出仓库表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageWarehouseModelInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportWarehouseModelOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "仓库表导出记录");
    }
    
    /// <summary>
    /// 下载仓库表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载仓库表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportWarehouseModelOutput>(), "仓库表导入模板");
    }
    
    private static readonly object _warehouseModelImportLock = new object();
    /// <summary>
    /// 导入仓库表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入仓库表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (_warehouseModelImportLock)
        {
            var stream = ExcelHelper.ImportData<ImportWarehouseModelInput, WarehouseModel>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.WareVolume == null){
                            x.Error = "仓库容量不能为空";
                            return false;
                        }
                        if (x.WareType == null){
                            x.Error = "仓库状态不能为空";
                            return false;
                        }
                        if (x.WareLock == null){
                            x.Error = "仓库锁定不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<WarehouseModel>>();
                    
                    var storageable = _warehouseModelRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.WareCode), "仓库编码不能为空")
                        .SplitError(it => it.Item.WareCode?.Length > 64, "仓库编码长度不能超过64个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.WareName), "仓库名称不能为空")
                        .SplitError(it => it.Item.WareName?.Length > 128, "仓库名称长度不能超过128个字符")
                        .SplitError(it => it.Item.WareAddr?.Length > 256, "仓库地址长度不能超过256个字符")
                        .SplitError(it => it.Item.WareNote?.Length > 512, "仓库备注长度不能超过512个字符")
                        .WhereColumns(it => new { it.WareName })
                        .SplitInsert(it=> !it.Any())
                        .SplitUpdate(it=> it.Any())
                        .ToStorage();
                    
                    storageable.AsInsertable.ExecuteCommand();// 不存在插入
                    storageable.AsUpdateable.UpdateColumns(it => new
                    {
                        it.WareCode,
                        it.WareName,
                        it.WareVolume,
                        it.DepartmentId,
                        it.UserId,
                        it.WareAddr,
                        it.WareType,
                        it.WareLock,
                        it.WareNote,
                        it.DeleteTime,
                    }).ExecuteCommand();// 存在更新
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
